﻿using FileTransfer.Assistantor;
using FileTransfer.Controls;
using FileTransfer.Model;
using HAF.LogUtility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace FileTransfer
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 运行时的缓存大小
        /// </summary>
        long runCacheSize = 1024 * 100;
        /// <summary>
        /// 运行时的线程数量
        /// </summary>
        int runThreadCount = 1;
        /// <summary>
        /// FTP方式 0 单线程 1 多线程 2 文件分块
        /// </summary>
        int runType = 1;
        /// <summary>
        /// 是否进行MD5计算
        /// </summary>
        bool needMd5 = false;
        
        int transferType;

        private void InitTransferParams()
        {
            string localAddress = ConfigurationManager.AppSettings.Get("LocalAddress");
            if (string.IsNullOrEmpty(localAddress))
            {
                localAddress = @"\\172.25.8.12\worksheet\FTP\";
            }
            LoadContext.DefaultSaveAddress = localAddress;

            transferType = System.Configuration.ConfigurationManager.AppSettings["TransferType"] != null
                ? int.Parse(System.Configuration.ConfigurationManager.AppSettings["TransferType"])
                : 1;

            runType = cmbModel.SelectedIndex;

            groupBox1.Visible = false;
            runThreadCount = runType == 2 ? (int)cmbThreadCount.Value : 1;
            //根据线程数量，确定Group大小
            //switch (runThreadCount)
            //{
            //    case 2:
            //        groupBox1.Height = 80;
            //        labProcess1.Visible = true;
            //        labProcess2.Visible = true;
            //        labProcess3.Visible = false;
            //        labProcess4.Visible = false;
            //        labProcess5.Visible = false;
            //        break;
            //    case 3:
            //        groupBox1.Height = 96;
            //        groupBox1.Visible = true;
            //        labProcess1.Visible = true;
            //        labProcess2.Visible = true;
            //        labProcess3.Visible = true;
            //        labProcess4.Visible = false;
            //        labProcess5.Visible = false;
            //        break;
            //    case 4:
            //        groupBox1.Height = 106;
            //        labProcess1.Visible = true;
            //        labProcess2.Visible = true;
            //        labProcess3.Visible = true;
            //        labProcess4.Visible = true;
            //        labProcess5.Visible = false;
            //        break;
            //    case 5:
            //        groupBox1.Height = 120;
            //        labProcess1.Visible = true;
            //        labProcess2.Visible = true;
            //        labProcess3.Visible = true;
            //        labProcess4.Visible = true;
            //        labProcess5.Visible = true;
            //        break;
            //    default: //1个线程
            //        groupBox1.Height = 60;
            //        labProcess1.Visible = true;
            //        labProcess2.Visible = false;
            //        labProcess3.Visible = false;
            //        labProcess4.Visible = false;
            //        labProcess5.Visible = false;
            //        break;
            //}
            groupBox1.Visible = true;

            string strCacheSize = cmbCacheSize.SelectedItem.ToString();
            if (strCacheSize.Equals("100KB"))
            {
                runCacheSize = 1024 * 100;
            }
            if (strCacheSize.Equals("200KB"))
            {
                runCacheSize = 1024 * 200;
            }
            if (strCacheSize.Equals("400KB"))
            {
                runCacheSize = 1024 * 400;
            }
            if (strCacheSize.Equals("600KB"))
            {
                runCacheSize = 1024 * 600;
            }
            if (strCacheSize.Equals("800KB"))
            {
                runCacheSize = 1024 * 800;
            }
            if (strCacheSize.Equals("1M"))
            {
                runCacheSize = 1024 * 1024 * 1;
            }
            if (strCacheSize.Equals("2M"))
            {
                runCacheSize = 1024 * 1024 * 2;
            }
            if (strCacheSize.Equals("3M"))
            {
                runCacheSize = 1024 * 1024 * 3;
            }
            if (strCacheSize.Equals("4M"))
            {
                runCacheSize = 1024 * 1024 * 4;
            }


            needMd5 = chkMD5.Checked;

            txtMsg.Clear();
            //progressBar1.Value = 0;
            //labPercentage.Text = string.Format("{0}%", 0);
            //labProcess1.Text = "Tread 0 real time status: {0} bytes received,Write File Position {0} bytes 0MB/s";
            //labProcess2.Text = "Tread 1 real time status: {0} bytes received,Write File Position {0} bytes 0MB/s";
            //labProcess3.Text = "Tread 2 real time status: {0} bytes received,Write File Position {0} bytes 0MB/s";
            //labProcess4.Text = "Tread 3 real time status: {0} bytes received,Write File Position {0} bytes 0MB/s";
            //labProcess5.Text = "Tread 4 real time status: {0} bytes received,Write File Position {0} bytes 0MB/s";
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            InitTransferParams();

            //if (lstUri.Items.Count > 0)
            //{
            //    //清空消息框
            //    txtMsg.Clear();
            //    btnDown.Enabled = false;
            //    ShowMessage("==========================================================");
            //    ShowMessage("启动新的下载流程");
            //    Thread runthread;
            //    //一对一线程 每个下载链接启用一个线程
            //    switch (runType)
            //    {
            //        case 1:  //多线程下载文件
            //            ShowMessage(string.Format("系统判定使用一对一进行下载，本次下载共有{0}个线程", lstUri.Items.Count));
            //            runthread = new Thread(new ThreadStart(MutliThread)) { Name = "downThread", IsBackground = true, Priority = ThreadPriority.Highest };
            //            runthread.Start();
            //            break;
            //        case 2:  //大文件按区块进行下载
            //            runthread = new Thread(delegate() { BigTransfer(lstUri.Items[0].ToString(), (int)cmbThreadCount.Value); }) { Name = "downThread", IsBackground = true, Priority = ThreadPriority.Highest };
            //            runthread.Start();
            //            break;
            //        default:  //单线程下载
            //            List<string> lstDown = new List<string>();
            //            foreach (var item in lstUri.Items)
            //            {
            //                lstDown.Add(item.ToString());
            //            }
            //            runthread = new Thread(delegate () { Transfer(lstDown); }) { Name = "downThread", IsBackground = true, Priority = ThreadPriority.Highest };
            //            runthread.Start();
            //            break;
            //    }
            //}
            //else
            //{
            //    ShowPopTips("请填写完整的FTP地址");
            //}
        }

        /// <summary>
        /// 大文件下载 多线程分块下载
        /// </summary>
        /// <param name="downUri">下载源地址</param>
        /// <param name="threadCount">处理线程数量</param>
        private void BigTransfer(string downUri, int threadCount)
        {
            ShowMessage(string.Format("准备下载资源{0}", downUri));
            //var resMeta = new MediaDownResult() { Code = (int)EnumFTPServiceCode.UnKnownErr, Message = "未知错误" };
            //string resSaveAddr = LoadContext.DefaultSaveAddress; // @"\\172.25.8.12\worksheet\FTP\";
            //string dateStr = Path.Combine(DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"));
            ////1、解析URI，并输出为FTP对象
            //FtpSiteParameters ftpCfg = FtpAssistantor.GetConfig(downUri);
            ////2、判断FTP服务器是否能链接
            //bool chkFtpState = CmdAssistant.GetInstance().Telnet(ftpCfg.IP, ftpCfg.Port);
            //if (!chkFtpState)
            //{
            //    ShowMessage(string.Format("FTP服务器{0}:{1}访问失败", ftpCfg.IP, ftpCfg.Port));
            //    return;
            //}
            //else
            //{
            //    ShowMessage(string.Format("FTP服务器{0}:{1}访问成功", ftpCfg.IP, ftpCfg.Port));
            //}
            ////3、获取资源后缀名
            //string fileExtName = Path.GetExtension(downUri);
            ////3、根据后缀名确定资源类型，并判断本地存储路径
            //string resFixDir = string.Empty;
            //if (fileExtName.ToLower() == ".mp4" || fileExtName.ToLower() == ".ts")
            //{
            //    resFixDir = "Movie";
            //    resMeta.ResType = EnumResType.Movie;
            //    ShowMessage(string.Format("当前文件{0}判定为视频资源", downUri));
            //}
            //if (fileExtName.ToLower() == ".jpg" || fileExtName.ToLower() == ".png")
            //{
            //    resFixDir = "Picture";
            //    resMeta.ResType = EnumResType.Picture;
            //    ShowMessage(string.Format("当前文件{0}判定为图片资源", downUri));
            //}
            //if (fileExtName.ToLower() == ".tar")
            //{
            //    resFixDir = "EPG";
            //    resMeta.ResType = EnumResType.Tar;
            //    ShowMessage(string.Format("当前文件{0}判定为封套包", downUri));
            //}

            ////4、远端资源文件名
            //string remotefilename = Path.GetFileName(downUri);
            ////本地存储目录名
            //string localDir = Path.Combine(resSaveAddr, resFixDir, dateStr);
            //if (!Directory.Exists(localDir))
            //{
            //    Directory.CreateDirectory(localDir);
            //}
            ////本地存储文件名
            //string localSaveFile = Path.Combine(resSaveAddr, resFixDir, dateStr, remotefilename);

            //ShowMessage(string.Format("资源下载信息：ServerIP:{0} Port:{1} UserName:{2} PassWord:{3} FileName:{4} SaveFileName:{5}", ftpCfg.IP, ftpCfg.Port,
            //            ftpCfg.UserId, ftpCfg.Password, ftpCfg.RemoteFile, localSaveFile));

            ////创建FTP对象
            //FtpAssistantor ftpManager = new FtpAssistantor(Guid.NewGuid(), ftpCfg.IP, ftpCfg.Port, "", ftpCfg.UserId, ftpCfg.Password);
            //ftpManager.CacheSize = (int)runCacheSize;
            ////指定消息输出代理，用于输出消息到Console
            //ftpManager.DownloadMessageEvent = ShowMessage;
            ////视频下载指定进度条
            //if (resMeta.ResType == EnumResType.Movie)
            //{
            //    //指定进度输出代理，用于输出进度信息到Console
            //    ftpManager.DownloadProcessChangeEvent = ShowProcess;
            //    ftpManager.DownloadChangeEvent = ShowStatus;
            //}

            //ShowMessage(string.Format("开始下载资源{0}", downUri));
            //ResponseLog rtn = ftpManager.MutliDownload(localSaveFile, ftpCfg.RemoteFile, threadCount);
            ////获取视频文件时长
            //if ((rtn.Code == (int)EnumFTPServiceCode.Success))
            //{
            //    //if (resMeta.ResType == EnumResType.Movie)
            //    //{
            //    //    resMeta.TimeStr = FileAssistantor.GetMediaTimeLen(localSaveFile);
            //    //    ShowMessage(string.Format("资源{0}时长为{1}", downUri, resMeta.TimeStr));
            //    //}
            //    ShowMessage(string.Format("资源{0}下载成功", downUri));
            //}
            //else
            //{
            //    ShowMessage(string.Format("资源{0}下载失败,{1}", downUri, rtn.Message));
            //}
            //UpdateBtnState(true);
            //if (downstat.Count > 0 && downstat.ContainsKey(downUri))
            //{
            //    downstat[downUri] = true;
            //}
        }

        Dictionary<string, bool> downstat = new Dictionary<string, bool>();
        private void MutliThread()
        {
            Stopwatch _stopwathc = Stopwatch.StartNew();
            _stopwathc.Start();

            int iNum = 0;
            downstat.Clear();

            //foreach (var item in lstUri.Items)
            {
                string downUri = ""; //item.ToString();
                ShowMessage(downUri);
                downstat.Add(downUri, false);
                Thread runthread = new Thread(delegate () { TransferThead(downUri); }) { Name = "downThread" + iNum.ToString(), IsBackground = true, Priority = ThreadPriority.Highest };
                runthread.Start();
                iNum++;
            }

            ShowMessage(string.Format("当前线程编号为{0}", System.Threading.Thread.CurrentThread.ManagedThreadId));

            while (true)
            {
                if (!downstat.ContainsValue(false))
                {
                    _stopwathc.Stop();
                    ShowMessage(string.Format("文件下载完成，共耗时{0}", _stopwathc.Elapsed.TotalSeconds > 60 ? _stopwathc.Elapsed.TotalMinutes.ToString() + "分" : _stopwathc.Elapsed.TotalSeconds.ToString() + "秒"));
                    //btnDown.Invoke(delegate() => { });
                    UpdateBtnState(true);
                    break;
                }
            }
        }

        private void UpdateBtnState(bool state)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<bool>(UpdateBtnState), state);
            }
            else
            {
                btnDown.Enabled = state;
            }
        }

        /// <summary>
        /// 文件传输线程
        /// </summary>
        /// <param name="downUri"></param>
        private void TransferThead(string downUri)
        {
            ShowMessage(string.Format("准备下载资源{0}", downUri));
            //var resMeta = new MediaDownResult() { Code = (int)EnumFTPServiceCode.UnKnownErr, Message = "未知错误" };
            //string resSaveAddr = LoadContext.DefaultSaveAddress; // @"\\172.25.8.12\worksheet\FTP\";
            //string dateStr = Path.Combine(DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"));
            ////1、解析URI，并输出为
            //FtpSiteParameters ftpCfg = FtpAssistantor.GetConfig(downUri);
            ////2、判断FTP服务器是否能链接
            //bool chkFtpState = CmdAssistant.GetInstance().Telnet(ftpCfg.IP, ftpCfg.Port);
            //if (!chkFtpState)
            //{
            //    ShowMessage(string.Format("FTP服务器{0}:{1}访问失败", ftpCfg.IP, ftpCfg.Port));
            //    return;
            //}
            //else
            //{
            //    ShowMessage(string.Format("FTP服务器{0}:{1}访问成功", ftpCfg.IP, ftpCfg.Port));
            //}
            ////2、获取资源后缀名
            //string fileExtName = Path.GetExtension(downUri);
            ////3、根据后缀名确定资源类型，并判断本地存储路径
            //string resFixDir = string.Empty;
            //if (fileExtName.ToLower() == ".mp4" || fileExtName.ToLower() == ".ts")
            //{
            //    resFixDir = "Movie";
            //    resMeta.ResType = EnumResType.Movie;
            //    ShowMessage(string.Format("当前文件{0}判定为视频资源", downUri));
            //}
            //if (fileExtName.ToLower() == ".jpg" || fileExtName.ToLower() == ".png")
            //{
            //    resFixDir = "Picture";
            //    resMeta.ResType = EnumResType.Picture;
            //    ShowMessage(string.Format("当前文件{0}判定为图片资源", downUri));
            //}
            //if (fileExtName.ToLower() == ".tar")
            //{
            //    resFixDir = "EPG";
            //    resMeta.ResType = EnumResType.Tar;
            //    ShowMessage(string.Format("当前文件{0}判定为封套包", downUri));
            //}

            ////4、远端资源文件名
            //string remotefilename = Path.GetFileName(downUri);
            ////本地存储目录名
            //string localDir = Path.Combine(resSaveAddr, resFixDir, dateStr);
            //if (!Directory.Exists(localDir))
            //{
            //    Directory.CreateDirectory(localDir);
            //}
            ////本地存储文件名
            //string localSaveFile = Path.Combine(resSaveAddr, resFixDir, dateStr, remotefilename);

            //ShowMessage(string.Format("资源下载信息：ServerIP:{0} Port:{1} UserName:{2} PassWord:{3} FileName:{4} SaveFileName:{5}", ftpCfg.IP, ftpCfg.Port,
            //            ftpCfg.UserId, ftpCfg.Password, ftpCfg.RemoteFile, localSaveFile));

            //if (transferType == 1)
            //{
            //    using (FluentFtpHelper ftpClient = new FluentFtpHelper(Guid.NewGuid(), ftpCfg.IP, ftpCfg.Port, "", ftpCfg.UserId, ftpCfg.Password))
            //    {
            //        //指定消息输出代理，用于输出消息到Console
            //        ftpClient.DownloadMessageEvent = ShowMessage;
            //        ftpClient.DownFile(localSaveFile, ftpCfg.RemoteFile);
            //    }

            //    if (chkDelay.Checked)
            //    {
            //        ShowMessage("进入延迟");
            //        Thread.Sleep(2000);
            //    }
            //}
            //else
            //{
            //    //创建FTP对象
            //    FtpAssistantor ftpManager = new FtpAssistantor(Guid.NewGuid(), ftpCfg.IP, ftpCfg.Port, "", ftpCfg.UserId, ftpCfg.Password);
            //    ftpManager.CacheSize = (int)runCacheSize;
            //    //指定消息输出代理，用于输出消息到Console
            //    ftpManager.DownloadMessageEvent = ShowMessage;
            //    //视频下载指定进度条
            //    if (resMeta.ResType == EnumResType.Movie)
            //    {
            //        //指定进度输出代理，用于输出进度信息到Console
            //        ftpManager.DownloadProcessChangeEvent = ShowProcess;
            //        ftpManager.DownloadChangeEvent = ShowStatus;
            //    }

            //    ShowMessage(string.Format("开始下载资源{0}", downUri));
            //    ResponseLog rtn = needMd5 ? ftpManager.DownloadWithMD5(localSaveFile, ftpCfg.RemoteFile) : ftpManager.Download(localSaveFile, ftpCfg.RemoteFile);
            //    //获取视频文件时长
            //    if ((rtn.Code == (int)EnumFTPServiceCode.Success))
            //    {
            //        //if (resMeta.ResType == EnumResType.Movie)
            //        //{
            //        //    resMeta.TimeStr = FileAssistantor.GetMediaTimeLen(localSaveFile);
            //        //    ShowMessage(string.Format("资源{0}时长为{1}", downUri, resMeta.TimeStr));
            //        //}
            //        ShowMessage(string.Format("资源{0}下载完成", downUri));
            //    }
            //    else
            //    {
            //        ShowMessage(string.Format("资源{0}下载失败", downUri));
            //    }
            //    if (downstat.Count > 0 && downstat.ContainsKey(downUri))
            //    {
            //        downstat[downUri] = true;
            //    }
            //}

        }

        /// <summary>
        /// 单线程下载
        /// </summary>
        /// <param name="lstDown"></param>
        private void Transfer(List<string> lstDown)
        {
            downstat.Clear();

            Stopwatch _stopwathc = Stopwatch.StartNew();
            _stopwathc.Start();

            foreach (var item in lstDown)
            {
                TransferThead(item);
            }
            _stopwathc.Stop();
            ShowMessage(string.Format("文件下载完成，共耗时{0}", _stopwathc.Elapsed.TotalSeconds > 60 ? _stopwathc.Elapsed.TotalMinutes.ToString() + "分" : _stopwathc.Elapsed.TotalSeconds.ToString() + "秒"));
            UpdateBtnState(true);
        }

        #region 下载进度控制
        private void ShowPopTips(string message)
        {
            MessageBox.Show(message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        int _msgLen = 0;

        private void ShowClear()
        {
            txtMsg.Clear();
        }

        private void ShowMessage(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(ShowMessage), msg);
            }
            else
            {
                //if (_msgLen >= 300)
                //{
                //    txtMsg.Clear();
                //    //txtMessages.Text = "";
                //    _msgLen = 0;
                //}
                LogHelper.WriteDebugLogEx("SysMonitor", msg);

                txtMsg.Text = txtMsg.Text + (DateTime.Now.ToString() + " " + msg + "\r\n");
                txtMsg.SelectionStart = txtMsg.Text.Length;
                txtMsg.ScrollToCaret();

                _msgLen++;

            }
        }

        private void ShowCaption(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(ShowCaption), msg);
            }
            else
            {
                //if (!LoadParams.AllowAutoModel)
                //{
                //    UpdateDownState(true);
                //    labDownFileName.Text = msg;
                //}
                //else
                //{
                //    UpdateDownState(false);
                //}
            }
        }

        /// <summary>
        /// 更新进度条
        /// </summary>
        /// <param name="percentage">百分比</param>
        private void ShowProcess(string threadId, int percentage)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, int>(ShowProcess), threadId, percentage);
            }
            else
            {

                //foreach (DataGridViewRow item in dgvTask.Rows)
                //{
                //    if (item.Cells[1].Value != null && item.Cells[1].Value.Equals(threadId))
                //    {
                //        item.Cells[13].Value = percentage;
                //        break;
                //    }
                //}

                //if (LoadParams.AllowAutoModel)
                {
                    FileStruct tmpRecord = runFileDownRecords.Find(t => t.ID == threadId);
                    if (tmpRecord != null)
                    {
                        foreach (DataGridViewRow item in dgvTask.Rows)
                        {
                            if (item.Cells[1].Value != null && item.Cells[1].Value.Equals(threadId))
                            {
                                item.Cells[17].Value = percentage;
                                break;
                            }
                        }
                    }

                }
                ShowMessage(percentage.ToString());
                //else
                //{
                //    labDownRate.Text = string.Format("{0}%", percentage);
                //    labDownProgress.Value = percentage;
                //}
                //this.progressBar1.Value = percentage;
                //labPercentage.Text = string.Format("{0}%", percentage);
            }

        }

        long MaxValue;
        long MinValue;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="threadId">下载线程编号</param>
        /// <param name="size">文件大小</param>
        /// <param name="receiveNum">已接收数量</param>
        /// <param name="position">已写入数量</param>
        /// <param name="flowsize">下载速率</param>
        private void ShowStatus(string threadId, long size, long receiveNum, long position, long flowsize)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, long, long, long, long>(ShowStatus), threadId, size, receiveNum, position, flowsize);
            }
            else
            {
                MaxValue = flowsize > MaxValue ? flowsize : MaxValue;
                MinValue = flowsize < MinValue ? flowsize : MinValue;
                string flowStr = flowsize > 1024 * 1024 ? string.Format("{0}MB/s", Math.Round((double)flowsize / (1024 * 1024), 2)) : string.Format("{0}KB/s", Math.Round((double)flowsize / 1024, 2));

                string sizeStr = FileAssistantor.GetLengthStr(size);
                //if (!LoadParams.AllowAutoModel)
                //{
                //    labDownSpeed.Text = flowStr;
                //}
                //else
                {
                    FileStruct tmpRecord = runFileDownRecords.Find(t => t.ID == threadId);
                    if (tmpRecord != null)
                    {
                        tmpRecord.Size = size;
                        foreach (DataGridViewRow item in dgvTask.Rows)
                        {
                            if (item.Cells[1].Value.Equals(threadId))
                            {
                                //item.Cells[6].Value = sizeStr;
                                item.Cells[15].Value = receiveNum;
                                item.Cells[16].Value = position;
                                item.Cells[18].Value = flowStr;
                                break;
                            }
                        }
                    }
                }
            }
        }
        #endregion 下载进度控制

        private void btnCheck_Click(object sender, EventArgs e)
        {
            //if (lstUri.Items.Count > 0)
            //{
            //    txtMsg.Clear();
            //    string uri = lstUri.Items[0].ToString();
            //    ShowMessage(string.Format("开始检测{0}的可访问性", uri));
            //    Thread thread = new Thread(delegate()
            //    {
            //        //提取IP和端口
            //        FtpConfig ftpCfg = FtpAssistantor.GetConfig(uri);

            //        string rtnStr = CmdAssistant.GetInstance().Ping(ftpCfg.IP);
            //        ShowMessage(rtnStr);

            //        bool rtn = CmdAssistant.GetInstance().Telnet(ftpCfg.IP, ftpCfg.Port);
            //        ShowMessage(string.Format("telnet {0} {1} {2}", ftpCfg.IP, ftpCfg.Port, rtn ? "成功" : "失败"));
            //    }) { Name = "checkThread", IsBackground = true, Priority = ThreadPriority.Normal };
            //    thread.Start();
            //}
            //else
            //{
            //    ShowPopTips("请填写完整的FTP地址");
            //}

        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            string txtDir = Path.Combine(Environment.CurrentDirectory, "down.txt");
            string[] lst = FileAssistantor.ReadSmallText(txtDir);
            //lstUri.Items.Clear();
            //foreach (var item in lst)
            //{
            //    lstUri.Items.Add(item);
            //}
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            runFileDownRecords.Clear();
            //lstUri.Items.Clear();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            InitUiControls();

            InitTransferParams();

            InitGrid();
        }

        private void InitUiControls()
        {
            //groupBox1.Height = 0;
            this.Text = string.Concat(LoadContext.AppCaption, " ", LoadContext.AppVersion);
            labAppName.Text = string.Concat(LoadContext.AppName, " ", LoadContext.AppVersion);
            labMediaName.Visible = false;
            labProgressBar.Visible = false;
            labRate.Visible = false;

            cmbModel.SelectedIndex = 0;
            cmbCacheSize.SelectedIndex = 0;
        }

        private void btnAddin_Click(object sender, EventArgs e)
        {
            FrmNewAddress frmAddress = new FrmNewAddress();
            if (frmAddress.ShowDialog() == DialogResult.OK)
            {
                //ftp://icms:rss123@223.85.241.34:21//icms/output-dsp/2023/10/25/17/tscjxm_tcmcciptv__a9151b7d711e425196b306e14d493611_1698225921147.xml
                MessageBox.Show(LoadContext.TempRemoteFileFullPath, "系统提示");
            }
        }

        #region DataGrid
        List<FileStruct> runFileDownRecords = new List<FileStruct>();
        List<FtpSiteParameters> runSites = new List<FtpSiteParameters>();

        private void InitGrid()
        {
            #region 任务表
            runFileDownRecords.Add(new FileStruct() { ID = "1", LocalPath = "", RemotePath = "", Size = 0 });
            dgvTask.AutoGenerateColumns = true;
            dgvTask.DataSource = runFileDownRecords;
            dgvTask.Columns[0].Visible = false;
            dgvTask.Columns[2].Visible = false;
            dgvTask.Columns[5].Visible = false;
            dgvTask.Columns[7].Visible = false;
            dgvTask.Columns[8].Visible = false;
            dgvTask.Columns[9].Visible = false;
            dgvTask.Columns[10].Visible = false;
            dgvTask.Columns[13].Visible = false;

            //设置对齐方式和字体
            dgvTask.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            dgvTask.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgvTask.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 11F, FontStyle.Bold);
            dgvTask.Font = new Font("宋体", 11);
            dgvTask.RowPostPaint += dgv_RowPostPaint;
            //dgvTask.ReadOnly = true;
            #endregion 任务表
        }

        private void dgvSearchColumnExt()
        {
            //0
            var chkColumn = new DataGridViewCheckBoxColumn();
            chkColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            chkColumn.HeaderText = "选择";
            chkColumn.FalseValue = false;
            chkColumn.TrueValue = true;
            chkColumn.DefaultCellStyle.NullValue = false;
            chkColumn.ReadOnly = false;
            dgvTask.Columns.Insert(0, chkColumn);

            var chkHeadCell = new DatagridviewCheckboxHeaderCell();
            chkHeadCell.OnCheckBoxClicked += new DatagridviewcheckboxHeaderEventHander(chkCell_OnCheckBoxClicked);
            var chkBoxHeadCell = dgvTask.Columns[0] as DataGridViewCheckBoxColumn;
            chkBoxHeadCell.HeaderCell = chkHeadCell;
            chkBoxHeadCell.HeaderCell.Value = string.Empty;

            //15
            var readnumColumn = new DataGridViewTextBoxColumn();
            readnumColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            readnumColumn.HeaderText = "读取数量";
            dgvTask.Columns.Add(readnumColumn);

            //16
            var writenumColumn = new DataGridViewTextBoxColumn();
            writenumColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            writenumColumn.HeaderText = "写入数量";
            dgvTask.Columns.Add(writenumColumn);

            //17
            var processColumn = new DataGridViewProgressBarColumn();
            //processColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            processColumn.Width = 120;
            processColumn.HeaderText = "进度";
            dgvTask.Columns.Add(processColumn);

            //18
            var ratenumColumn = new DataGridViewTextBoxColumn();
            ratenumColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            ratenumColumn.HeaderText = "下载速度";
            dgvTask.Columns.Add(ratenumColumn);

            //设置CheckBox默认值
            for (int i = 0; i < dgvTask.Rows.Count; i++)
            {
                dgvTask.Rows[i].Cells[0].Value = false;
            }
            dgvTask.EndEdit();
        }

        private void chkCell_OnCheckBoxClicked(object sender, DatagridviewCheckboxHeaderEventArgs e)
        {
            dgvTask.EndEdit();

            if (e.CheckedState)
            {
                for (int i = 0; i < dgvTask.Rows.Count; i++)
                {
                    dgvTask.Rows[i].Cells[0].Value = true;
                }
                //foreach (DataGridViewRow dgvRow in this.dgv.Rows)
                //{
                //    dgvRow.Cells["dataGridViewCheckBoxColumn1"].Value = true;
                //}
            }
            else
            {
                for (int i = 0; i < dgvTask.Rows.Count; i++)
                {
                    dgvTask.Rows[i].Cells[0].Value = false;
                }
                //foreach (DataGridViewRow dgvRow in this.dgv.Rows)
                //{
                //    dgvRow.Cells["dataGridViewCheckBoxColumn1"].Value = 0;
                //}
            }

            //dgvSearch.RefreshEdit();
        }

        /// <summary>
        /// 处理行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //行头显示行号
            var grid = sender as DataGridView;
            var rowidx = (e.RowIndex + 1).ToString();
            var centerFormat = new StringFormat()
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
            var headerBuunds = new System.Drawing.Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowidx, new Font("宋体", 11), SystemBrushes.ControlText, headerBuunds, centerFormat);
        }

        /// <summary>
        /// 隔行变色
        /// </summary>
        /// <param name="sender"></param>
        private void DgvRowColor(DataGridView sender)
        {
            if (sender.Rows.Count != 0)
            {
                for (int i = 0; i < sender.Rows.Count; i++)
                {
                    if ((i + 1) % 2 == 0)
                    {
                        sender.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.White;
                    }
                    else
                    {
                        sender.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(224, 254, 254);
                    }
                }
            }
        }

        private void BindGrid(List<FileStruct> runFiles)
        {
            dgvTask.DataSource = null;
            dgvTask.Columns.Clear();
            dgvTask.Rows.Clear();
            dgvTask.DataSource = runFiles;

            dgvSearchColumnExt();

            dgvTask.Columns[1].Visible = false;
            dgvTask.Columns[3].Visible = false;
            dgvTask.Columns[7].Visible = false;
            dgvTask.Columns[8].Visible = false;
            dgvTask.Columns[9].Visible = false;
            dgvTask.Columns[10].Visible = false;
            dgvTask.Columns[11].Visible = false;
            dgvTask.Columns[12].Visible = false;
            dgvTask.Columns[13].Visible = false;
            dgvTask.Columns[14].Visible = false;

            dgvTask.Columns[2].Width = 140;
            dgvTask.Columns[4].Width = 260;
            dgvTask.Columns[5].Width = 260;
            
            DgvRowColor(dgvTask);
        }
        #endregion DataGrid

        private void btnExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            FrmNewAddress frmAddress = new FrmNewAddress();
            if (frmAddress.ShowDialog() == DialogResult.OK)
            {
                //ftp://icms:rss123@223.85.241.34:21//icms/output-dsp/2023/10/25/17/tscjxm_tcmcciptv__a9151b7d711e425196b306e14d493611_1698225921147.xml
                //ShowPopTips(LoadContext.TempRemoteFileFullPath);

                FtpSiteParameters runFtpConfig = FtpParser.ParseStr(LoadContext.TempRemoteFileFullPath, LoadContext.AllowGuidName);
                if (runFtpConfig != null && runFtpConfig.FileSets != null && runFtpConfig.FileSets.Count > 0)
                {
                    if (runSites.Exists(t =>t.Site == runFtpConfig.Site))
                    {
                        var tmpSite = runSites.Find(t => t.Site == runFtpConfig.Site);
                        tmpSite.FileSets.AddRange(runFtpConfig.FileSets);
                    }
                    else
                    {
                        runSites.Add(runFtpConfig);
                    }
                    
                    runFileDownRecords.RemoveAll(t => t.ID == "1");
                    runFileDownRecords.AddRange(runFtpConfig.FileSets);
                    BindGrid(runFileDownRecords);
                }
            }
        }

        private void btnFileDown_Click(object sender, EventArgs e)
        {
            if (dgvTask.Rows.Count > 0)
            {
                //先将所有内容设置为不下载
                foreach (var item in runFileDownRecords)
                {
                    item.BEnable = false;
                }
                //获取DataGrid中勾选的任务
                foreach (DataGridViewRow item in dgvTask.Rows)
                {
                    //Console.WriteLine(item.Cells[0].Value);
                    if (item.Cells[0].Value.ToString().ToLower().Equals("true"))
                    {
                        //Console.WriteLine(item.Cells[1].Value);
                        string id = item.Cells[1].Value.ToString();
                        FileStruct tmpFile = runFileDownRecords.Find(t => t.ID == id);
                        if (tmpFile != null)
                        {
                            tmpFile.BEnable = true;
                        }

                    }
                }

                runFileDownRecords.RemoveAll(t => t.BEnable == false);
                if (runFileDownRecords != null && runFileDownRecords.Count > 0)
                {
                    runSites.ForEach(t=> t.FileSets.Clear());

                    foreach (var item in runFileDownRecords)
                    {
                        if (runSites.Exists(t => t.Site == item.Site))
                        {
                            runSites.Find(t => t.Site == item.Site).FileSets.Add(item);
                        }
                    }

                    int i = 0;
                    foreach (var item in runSites)
                    {
                        Thread thread = new Thread(delegate ()
                        {
                            //LoadParams.AllowAutoModel = true;
                            using (MediaGather gather = new MediaGather(new ControlParams()))
                            {
                                gather.WriteConsolMessageEvent = ShowMessage;
                                gather.DownloadChangeEvent = ShowStatus;
                                //gather.RefreshGridEvent = BindTaskData;
                                //gather.GatherEndEvent = GatherError;
                                gather.WriteStripCaptionEvent = ShowCaption;  //标题展示
                                gather.WriteProcessEvnet = ShowProcess;
                                gather.Down(item);
                            };
                        })
                        { Name = string.Format("gather{0}", i), IsBackground = true};
                        thread.Start();
                        i++;
                    }
                    


                }
            }
        }
    }
}
